/**
 * @Author: Sun Rising
 * @Date: 2022-01-01 10:01:49
 * @Last Modified by: Sun Rising
 * @Last Modified time: 2022-01-09 11:40:52
 * @Description: 项目主线程入口文件
 */
import {
  app,
  BrowserWindow,
  HandlerDetails,
  protocol,
  ProtocolRequest,
  session,
  WebContents,
} from "electron";
import * as path from "path";
import { extname } from "path";
import { initIpc } from "./ipc";
import { protocolHandle } from "./task/protocol-handle";

initIpc();

const isDevelopment = process.env.NODE_ENV !== "production";

// global reference to mainWindow (necessary to prevent window from being garbage collected)
let mainWindow: BrowserWindow | null;

function createMainWindow() {
  // 欢迎页面不使用 preload 注入的原因：开发模式下为不影响热更新 contextIsolation 需关闭，而使用 preload 需要开启 contextIsolation 故启用 nodeIntegration 放弃 preload
  const window = new BrowserWindow({
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      // webSecurity: false,
      // preload: join(app.getAppPath(), "preload.js"),
    },
  });

  // const window2 = new BrowserWindow({
  //   webPreferences: {
  //     nodeIntegration: true,
  //     contextIsolation: true,
  //     preload: join(app.getAppPath(), "preload.js"),
  //   },
  // });

  if (isDevelopment) {
    window.webContents.openDevTools();
  }

  if (isDevelopment) {
    window.loadURL(`http://localhost:${process.env.ELECTRON_WEBPACK_WDS_PORT}`);
  } else {
    window.loadURL(`file://${path.join(__dirname, "index.html")}`);
  }

  // window2.loadURL(`http://127.0.0.1:5500/asf/pdfaa.pdf`);

  window.on("closed", () => {
    mainWindow = null;
  });

  window.webContents.on("devtools-opened", () => {
    window.focus();
    setImmediate(() => {
      window.focus();
    });
  });

  window.webContents.session.on("will-download", (event, item, webContents) => {
    try {
      // 获取扩展名
      const ext = extname(item.getFilename());
      item.setSaveDialogOptions({
        filters: [
          { name: "当前文件", extensions: [ext.split(".")[1]] },
          { name: "所有文件", extensions: ["*"] },
        ],
      });
    } catch (error) {
      console.warn("will-download 设置 filters 失败", error);
    }
  });

  let a = window.webContents.session.getAllExtensions();

  console.log(a);

  return window;
}

// app.on("web-contents-created", (event: Event, webContents: WebContents) => {
//   webContents.on("will-navigate", (event: Event, url: string) => {
//     console.log("will-navigate", url, event);
//     event.preventDefault();
//     webContents.downloadURL(url);
//   });
//   webContents.setWindowOpenHandler((details: HandlerDetails) => {
//     let { url } = details;
//     console.log("setWindowOpenHandler", url);
//     webContents.downloadURL(url);
//     return { action: "deny" };
//     return { action: "allow" };
//   });
// });

// quit application when all windows are closed
app.on("window-all-closed", () => {
  // on macOS it is common for applications to stay open until the user explicitly quits
  // if (process.platform !== "darwin") {
  // app.quit();
  app.exit(1);
  // }
});
app.on("will-quit", (event) => {
  event.preventDefault();
  app.exit(1);
});

app.on("activate", () => {
  // on macOS it is common to re-create a window even after all windows have been closed
  if (mainWindow === null) {
    mainWindow = createMainWindow();
  }
});

// create main BrowserWindow when electron is ready
app.on("ready", () => {
  const webReqFilter = {
    urls: ["*://*/*"],
  };

  // protocol.interceptFileProtocol
  session.defaultSession.webRequest.onBeforeRequest(
    webReqFilter,
    function (details, callback) {
      // console.log("webRequest.onBeforeRequest", details);
      // callback({ cancel: false, redirectURL: 'https://cn.bing.com/'});
      callback({});
    }
  );

  // Returns Boolean - Whether the protocol was successfully intercepted
  protocol.interceptFileProtocol("file", (request, callback) => {
    // console.log('protocol.interceptFileProtocol', request);
    // callback({ statusCode: 400, data: 'Host Not Allowed' });
    // const url = request.url.substr(8);
    // var fPath = `file://${__dirname}/dist/index.html`;
    var fPath = request.url.substr(8); // 截取file:///之后的内容，也就是我们需要的

    fPath = path.normalize(fPath);
    console.log("protocol.interceptFileProtocol", fPath);
    callback({ path: fPath });
    return true;
  });

  mainWindow = createMainWindow();
});

// app.on("open-url", (event, url) => {
//   console.log("open-url", url);
// });
// app.on("open-file", (event, url) => {
//   console.log("open-file", url);
// });

app.whenReady().then(() => {
  protocolHandle();
});
